/* Includes ----------------------------------------------------------------- */
#include "../bsp/bsp_tim.h"

#include <gpio.h>
#include <main.h>

/* Private define ----------------------------------------------------------- */
#define PI_2 (3.14159f * 2)
#define TIM_PERIOD 100.0f
#define CNT_RESET 0u

#define ENCODER_MULTIPLE 4 /*编码器倍频，通过定时器的编码器模式设置*/
#define ENCODER_RES \
  (360.0f / 4.0f * ENCODER_MULTIPLE) /* PPR = CPR/4 * 四倍频 */
#define MOTOR_RED_RATIO 34.0f        /* 减速比 */
#define ENCODER_TAL_RES (ENCODER_RES * MOTOR_RED_RATIO) /* 总脉冲数 */
/*电机转一圈总的脉冲数(定时器能读到的脉冲数) =
 * 编码器物理脉冲数*编码器倍频*电机减速比 */
/* M法： 10ms采样脉冲数/(编码器总脉冲数*每次10ms)*/
/* 小车转轴转一圈，定时器计数*/
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
/* Private variables -------------------------------------------------------- */
/* Private function  -------------------------------------------------------- */
/* Exported functions ------------------------------------------------------- */

/**
 * @brief  Period elapsed callback in non blocking mode
 * @note   This function is called  when TIM2 interrupt took place, inside
 * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
 * a global variable "uwTick" used as application time base.
 * @param  htim : TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
  if (htim->Instance == TIM1) {
  }

  if (htim->Instance == TIM2) {
    HAL_IncTick();
  }
  if (htim->Instance == TIM3) {
  }
  if (htim->Instance == TIM4) {
  }
}
int8_t BSP_Delay(uint32_t ms) {
  uint32_t tick_period = 1000u / osKernelGetTickFreq();
  uint32_t ticks = ms / tick_period;

  switch (osKernelGetState()) {
    case osKernelError:
    case osKernelReserved:
    case osKernelLocked:
    case osKernelSuspended:
      return HAL_ERROR;

    case osKernelRunning:
      osDelay(ticks ? ticks : 1);
      break;

    case osKernelInactive:
    case osKernelReady:
      HAL_Delay(ms);
      break;
  }
  return HAL_OK;
}
